package com.kuqi.controller;

import com.kuqi.Enumeration.ResponseCode;
import com.kuqi.dao.BannerRepository;
import com.kuqi.dao.PromotionRepository;
import com.kuqi.entity.BannerInfo;
import com.kuqi.entity.PromotionInfo;
import net.minidev.json.JSONArray;
import net.minidev.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@Controller
public class PromotionController {

    @Autowired
    PromotionRepository promotionRepository;

    // 展现轮播图 参数为轮播图数量限制
    @ResponseBody
    @RequestMapping(value = "/app/getPromotion.html", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    public String getPromotion(@RequestBody JSONObject jsonParam) {
        System.out.println(jsonParam.toJSONString());
        //获取参数并查询
        int limit = Integer.parseInt(jsonParam.get("limitNum").toString());
        List<PromotionInfo> banners = promotionRepository.findWithLimit(limit);
        JSONObject result = new JSONObject();
        if(banners == null || banners.size() <= 0){ // 查询不到
            result.put("code", ResponseCode.NORESULT.getCode());
            result.put("msg",ResponseCode.NORESULT.getValue());
            result.put("data",null);
        }else{
            result.put("code",ResponseCode.SUCCESS.getCode());
            result.put("msg",ResponseCode.SUCCESS.getValue());
            JSONArray arr = new JSONArray();
            for(PromotionInfo item : banners){
                arr.add(item.toJsonObject());
            }
            result.put("data",arr);
        }
        return result.toJSONString();
    }

}